﻿'use strict';

/* ****************************************************************
WebServiceProxy:
+ Events:
    + after
    + before
    + failed
    + success
**************************************************************** */

/*global module, exports, define, ActiveXObject*/
(function (global, factory) {
    if (typeof exports === 'object') {
        // Node
        module.exports = factory();
    }
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(factory);
    }
    
    //// Browser globals
    //global.WebServiceProxy = factory();

}(typeof window !== "undefined" ? window : this, function () {
    var WebServiceProxy = utils.BaseClass.extend({
        defaults: {
            contentType: "application/json",
            url: '',
            verb: 'POST',
        },

        request: function (method, data, options) {
            options || (options = {});

            var that = this,
                fn_success = function (response) {
                    var responseParsed = JSON.parse(response);

                    if (options.success)
                        options.success(responseParsed);

                    that.trigger('success', this, responseParsed, method)
                        .trigger(sprintf('success:%s', method), this, responseParsed, method)
                        .trigger('after', this, method)
                        .trigger(sprintf('after:%s', method), this, method);
                },
                fn_error = function (jqReq, errorMsg, status) {
                    if (options.error)
                        options.error(jqReq, errorMsg, status);

                    that.trigger('failed', this, jqReq, errorMsg, status, method)
                        .trigger(sprintf('failed:%s', method), this, jqReq, errorMsg, status, method)
                        .trigger('after', this, method)
                        .trigger(sprintf('after:%s', method), this, method);
                };

            this.trigger('before', this, method, data)
                .trigger(sprintf('before:%s', method), this, method, data);

            $.ajax(_.extend(
                this.attributes,
                {
                    url: this.attributes.url + method,

                    data: JSON.stringify(data),
                    error: fn_error,
                    success: fn_success,
                },
                options
            ));
        },
    });

    return WebServiceProxy;
}));